package com.workManager.controller;

import com.github.pagehelper.PageInfo;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.workManager.base.BaseController;
import com.workManager.config.RespCode;
import com.workManager.pojo.TdRole;
import com.workManager.service.RoleService;
import com.workManager.vo.RoleFunctionVo;
import com.workManager.vo.RoleVo;
import com.workManager.vo.TempVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by Thinkpad on 2017/3/3 0003.
 */
@Controller
@RequestMapping("/role")
public class RoleController extends BaseController {


    @Autowired
    private RoleService roleService;

    @ApiOperation(value ="角色添加",notes = "角色添加")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Object add(HttpServletRequest request, @RequestBody TdRole role){
        ModelMap modelMap = new ModelMap();
        role.setIsValid(true);
        role.setCreateDate(new Date());


        /*Map<String,Object> map = new HashMap<String, Object>();
        map.put("roleName",role.getRoleName());
        PageInfo<RoleVo> rolePageInfo = roleService.query(map);
        if(rolePageInfo.getTotal()>0){

            List<RoleVo> roleList = rolePageInfo.getList();
            for(TdRole role1:roleList){
                if(role1.getRoleName().equals(role.getRoleName())){
                    return setModelMap(modelMap, RespCode.INTERNAL_SERVER_ERROR,"角色名："+role.getRoleName()+" 已存在！");
                }
            }


        }*/

        try{
            roleService.add(role);
        }catch (DuplicateKeyException e){
            return setModelMap(modelMap,RespCode.INTERNAL_SERVER_ERROR,"角色名："+role.getRoleName()+" 已存在！");
        }


        return  setSuccessModelMap(modelMap);
    }
    @ApiOperation(value ="角色更新",notes = "角色更新")
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Object update(HttpServletRequest request, @RequestBody TdRole role){
        ModelMap modelMap = new ModelMap();
        role.setIsValid(true);


        //校验角色名有没有冲突
        /*Map<String,Object> map = new HashMap<String, Object>();
        map.put("roleId",role.getRoleId());
        PageInfo<RoleVo> rolePageInfo = roleService.query(map);
        if(rolePageInfo.getTotal()>1){
            TdRole role1 = rolePageInfo.getList().get(0);
            if(role1.getRoleName()!=null&&!role1.getRoleName().equals(role.getRoleName())){
                Map<String,Object> map1 = new HashMap<String, Object>();
                map1.put("roleName",role.getRoleName());
                PageInfo<RoleVo> rolePageInfo1 = roleService.query(map1);
                if(rolePageInfo1.getTotal()>1){
                    return  setModelMap(modelMap,RespCode.INTERNAL_SERVER_ERROR,"角色名："+role.getRoleName()+" 已存在！");
                }
            }

        }*/

        try {
            roleService.update(role);
        }catch (DuplicateKeyException e){
            return setModelMap(modelMap,RespCode.INTERNAL_SERVER_ERROR,"角色名："+role.getRoleName()+"已存在！");
        }


        return setSuccessModelMap(modelMap);
    }

    @ApiOperation(value ="角色查询",notes = "角色查询")
    @RequestMapping(value = "/query",method = RequestMethod.POST)
    public Object query(HttpServletRequest request,@RequestParam(value = "pageNumber",required = false) String pageNumber,
                        @RequestParam(value="pageSize", required = false) String pageSize,
                        @ApiParam(required = true, value = "角色名")@RequestParam(value = "roleName",required = false) String roleName){

        ModelMap modelMap = new ModelMap();
        Map<String,Object> map = new HashMap<String, Object>();
        Integer pagenum = pageNumber==null?1:Integer.parseInt(pageNumber);
        Integer pagesize = pageSize==null?10:Integer.parseInt(pageSize);

        Map parammap = new HashMap();
        parammap.put("pagenum",pagenum);
        parammap.put("pagesize",pagesize);
        parammap.put("roleName",roleName);

        System.out.println("roleName:-------------"+roleName);

        PageInfo<RoleVo> role = roleService.query(parammap);
        map.put("total",role.getTotal());
        map.put("rows",role.getList());
        return  setSuccessModelMap(modelMap,map);
    }

    @ApiOperation(value ="角色删除",notes = "角色删除")
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public Object delete(HttpServletRequest request, @RequestParam(value = "roleId",required = false) String roleId){

        ModelMap modelMap = new ModelMap();
        try{
            roleService.delete(roleId);
        }catch (DataIntegrityViolationException e){
            return setModelMap(modelMap, RespCode.INTERNAL_SERVER_ERROR, "该角色下面有关联用户,不能删除！");
        }
        return  setSuccessModelMap(modelMap);
    }

    @ApiOperation(value ="角色批量删除",notes = "角色批量删除")
    @RequestMapping(value = "/deleteByList",method = RequestMethod.POST)
    public Object deleteByList(@RequestParam(value = "roleIds",required = false) List<String> roleIds){

        ModelMap modelMap = new ModelMap();
        try{
            roleService.deleteByList(roleIds);
        }catch (DataIntegrityViolationException e){
            return setModelMap(modelMap, RespCode.INTERNAL_SERVER_ERROR, "角色下面有关联用户，不能删除！");
        }
        return  setSuccessModelMap(modelMap);
    }

    @ApiOperation(value ="用户功能插入",notes = "用户功能插入")
    @RequestMapping(value = "/insertRoleFunction",method = RequestMethod.POST)
    public Object insertRoleFunction(HttpServletRequest request,
                                     @RequestBody TempVo vo){
        String roleId = vo.getRoleId();
        String functionIds = vo.getFunctionIds();
        ModelMap modelMap = new ModelMap();


        //插入之前先将之前的数据置失效
        roleService.deleteRoleFunctionByRoleId(Integer.parseInt(roleId));


        if(functionIds==null){
            return setSuccessModelMap(modelMap);
        }

        String[] functionList = functionIds.split(",");




        /*for(int i =0;i< functionList.length;i++){
            TdRoleFunction roleFunction = new TdRoleFunction();
            roleFunction.setIsValid(true);
            roleFunction.setCreateDate(new Date());
            roleFunction.setFunctionId(Integer.parseInt(functionList[i]));
            roleFunction.setRoleId(Integer.parseInt(roleId));
            roleService.insertRoleFunction(roleFunction);
        }*/
        List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();
        for(int i=0;i<functionList.length;i++){
            Map map = new HashMap();
            map.put("roleId",roleId);
            map.put("functionId",functionList[i]);
            list.add(map);
        }

        roleService.insertRoleFunctionBatch(list);
        return  setSuccessModelMap(modelMap);

    }

    @ApiOperation(value ="用户功能查询",notes = "用户功能查询")
    @RequestMapping(value = "/queryRoleFunction",method = RequestMethod.POST)
    public Object queryRoleFunction(HttpServletRequest request,@RequestParam(value = "pageNumber",required = false) String pageNumber,
                                    @RequestParam(value="pageSize", required = false) String pageSize, @RequestParam(value = "roleId",required = false) String roleId){

        ModelMap modelMap = new ModelMap();

        List<Map<String,Object>> listMap = new ArrayList<Map<String, Object>>();
        Integer pagenum = pageNumber==null?1:Integer.parseInt(pageNumber);
        Integer pagesize = pageSize==null?10:Integer.parseInt(pageSize);
        Map parammap = new HashMap();
        parammap.put("pagenum",pagenum);
        parammap.put("pagesize",pagesize);
        parammap.put("roleId",roleId);
        PageInfo<RoleFunctionVo> roleFunctionVoPageInfo = roleService.queryRoleFunction(parammap);

        List<RoleFunctionVo> list = roleFunctionVoPageInfo.getList();
        Set<String> set = new HashSet();
        for(RoleFunctionVo roleFunctionVo:list){
            set.add(roleFunctionVo.getGroupCode());
        }
        Iterator s = set.iterator();
        while(s.hasNext()){
            String groupCode = s.next().toString();
            Map m = new HashMap();
            List<RoleFunctionVo> roleFunctionVoList = new ArrayList<RoleFunctionVo>();
            for (RoleFunctionVo roleFunctionVo:list){
                if(groupCode.equals(roleFunctionVo.getGroupCode())){
                    roleFunctionVoList.add(roleFunctionVo);
                }
            }
            m.put("groupName",groupCode);
            m.put("function",roleFunctionVoList);
            listMap.add(m);
        }
        return setSuccessModelMap(modelMap,listMap);
    }

    @ApiOperation(value ="用户功能Id查询",notes = "用户功能Id查询")
    @RequestMapping(value = "/queryRoleFunctionId",method = RequestMethod.POST)
    public Object queryRoleFunctionId(HttpServletRequest request, @RequestParam(value = "roleId",required = false) String roleId){

        ModelMap modelMap = new ModelMap();


        List<String> functionIds = roleService.queryRoleFunctionId(roleId);



        return setSuccessModelMap(modelMap,functionIds);




    }







}
